#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
import subprocess
import datetime
import argparse
from googleAccount import *

def mail(to, subject, text, attach):
   msg = MIMEMultipart()
   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   if attach:
      part = MIMEBase('application', 'octet-stream')
      part.set_payload(open(attach, 'rb').read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition',
              'attachment; filename="%s"' % os.path.basename(attach))
      msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to.split(","), msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

# use opt parse to get command line args
if __name__ == "__main__":
   parser = argparse.ArgumentParser(description='report ip address to gmail')
   parser.add_argument('--note', dest='note', default='',
                       help='enter a note that will be included in subject line')
       
   args = parser.parse_args()

   tStr =  datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

   arg='ip route list'
   p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
   data = p.communicate()
   split_data = data[0].split()
   ipaddr = split_data[split_data.index('src')+1]
   body = 'Your ip is %s' %  ipaddr
   subject = args.note + ' ' + ipaddr + ' For RaspberryPi on ' + tStr

   mail(dest_addr, subject, body, '')
